from pdf2image import convert_from_path
from flask import current_app as app
import os
from utils import get_file_info


def do_pdf_2_img(filename):
    # PDF文件路径
    pdf_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    print("pdf_path:", pdf_path)
    dpi = 300  # 分辨率，单位为DPI

    # 将PDF转换为图片
    # 输出目录
    file_info = get_file_info(filename)
    output_folder = os.path.join(app.config['DOWNLOAD_FOLDER'], file_info[0])
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    print("output_folder:", output_folder)

    images = convert_from_path(pdf_path,
                               dpi=dpi,
                               output_folder=output_folder,
                               thread_count=4,
                               fmt="jpg")
    print("the number of images:", len(images))

    return output_folder    # /static/2img/example_1212414

    # zip_path = os.path.join(app.config['DOWNLOAD_FOLDER'], get_file_info(filename)[0], "target.zip")
    # print("zip_path:", zip_path)
    # print("start zip")
    # zip_folder(output_folder, zip_path)
    #
    # return zip_path

    # 将多个图片连接成一张长图
    # combined_image = Image.new('RGB', (images[0].width, sum(img.height for img in images)))
    #
    # y_offset = 0
    # for image in images:
    #     combined_image.paste(image, (0, y_offset))
    #     y_offset += image.height
    #
    # # 图片命名
    # file_info = get_file_info(filename)
    # new_file = file_info[0] + ".jpg"
    # # 保存合并后的图片
    # img_path = os.path.join(app.config['DOWNLOAD_FOLDER'], new_file)
    # print("img_path:", img_path)
    #
    # combined_image.save(img_path, 'JPEG')
    # return img_path
